library AmmunitionFeed initializer init requires LegacySystem, AmmoAPI

	private function AmmoFeedConditions takes nothing returns boolean
		return GetSpellAbilityId()=='A00M'
	endfunction

	private function AmmoFeed takes nothing returns nothing
		local unit u = GetTriggerUnit()
		local player p = GetOwningPlayer(u)
		local integer i = GetConvertedPlayerId(p)
		local integer r = udg_Reloading[i]
		local real factor = I2R(GetUnitAbilityLevel(udg_Hero[i],'A00M'))*0.5
		
		if (r==0 or r==4) and GetPrimaryAmmoMagazines(p) !=0 and GetUnitUserData(u)-GetPrimaryAmmoRounds(p)>=100 then
			call TriggerSleepAction(0.1)
		endif
		if (r==0 or r==4) and GetPrimaryAmmoMagazines(p) !=0 and GetUnitUserData(u)-GetPrimaryAmmoRounds(p)>=100 then
			call UnitAddAbility(udg_Hero[i],'A02H') //Reload Animation
			call UnitAddAbility(udg_Hero[i],'A07Y') //500 Sight range reduction
			call ShiftMoveSpeed(udg_Hero[i],1.4)
			call PauseUnit(udg_Hero[i],true)
			call TriggerSleepAction(3.55-factor)
		
			call AddPrimaryAmmo(u, -1, 100) 
			call MachineGunLink(udg_Hero[i])
			call PauseUnit(udg_Hero[i],false)
			call TriggerSleepAction(0.65)
			set bj_meleeNearestMineDist = GetUnitX(udg_Hero[i])
			set bj_lastTransmissionDuration = GetUnitY(udg_Hero[i])
			set udg_soundpath = "war3mapImported\\Reload.wav"
			call PlaySoundPath3D.execute()
			call UnitRemoveAbility(udg_Hero[i],'A02H')
			call UnitRemoveAbility(udg_Hero[i],'A07Y') //500 Sight range reduction
		else
			call IssueImmediateOrder(udg_Hero[i],"holdposition")
			call DisplayTimedTextToPlayer( p, 0, 0, 5.0, "Ammunition Feed cannot be used now." )
		endif
		set u = null
	endfunction

	private function MGAmmoFeedLearn takes nothing returns boolean
		if GetLearnedSkill() == 'A00M' then
			call SetUnitUserData(GetTriggerUnit(),GetUnitUserData(GetTriggerUnit())+100)
		endif
		return false
	endfunction
		
	private function init takes nothing returns nothing
		local trigger t
		set t = CreateTrigger()
		call TriggerRegisterAnyUnitEventBJ( t, EVENT_PLAYER_UNIT_SPELL_EFFECT )
		call TriggerAddCondition(t,Condition(function AmmoFeedConditions))
		call TriggerAddAction(t,function AmmoFeed)
	
		set t = CreateTrigger()
		call TriggerRegisterAnyUnitEventBJ( t, EVENT_PLAYER_HERO_SKILL )
		call TriggerAddCondition(t,Condition(function MGAmmoFeedLearn))
		
	endfunction


endlibrary